package com.demo.多线程;

/**
 * @Program: Java
 * @ClassName synchronizedLock
 * @Description: synchronized的生产者消费者问题
 * @Author: liutao
 * @Create: 2024/5/30 15:13
 * @Version 1.0
 **/
public class synchronizedLock {
    public static void main(String[] args) {
        synchronizedData data = new synchronizedData();
        new Thread(() -> {
            try {
                data.increase();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "A").start();

        new Thread(() -> {
            try {
                data.decrease();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "B").start();
    }
}

class synchronizedData {
    private int num = 0;

    public synchronized void increase() throws InterruptedException {
        if (num != 0) {
            this.wait();
        }
        num++;
        System.out.println(Thread.currentThread().getName() + ":res:" + num);
        this.notifyAll();
    }


    public synchronized void decrease() throws InterruptedException {
        if (num == 0) {
            this.wait();
        }
        num--;
        System.out.println(Thread.currentThread().getName() + ":res:" + num);
        this.notifyAll();
    }
}
